﻿namespace WMS6.SQLServerDAL
{
    using System;
    using System.Collections.Generic;
    using System.Data;
    using System.Data.Common;
    using System.Data.SqlClient;
    using System.Text;
    using WMS6.Common;
    using WMS6.DataEntity;
    using WMS6.DBUtility;
    using WMS6.IDAL;
    using WMS6.QueryEntity;

    public class UserCarrierDA : IUserCarrierDA
    {
        private string CARRIER_ID = "@CARRIER_ID";
        private string CREATED_BY = "@CREATED_BY";
        private string IS_DEFAULT = "@IS_DEFAULT";
        private string SQL_CHECK_USER_CARRIER_ID_UNIQUE = " SELECT COUNT(1) FROM @_@USER_CARRIER WHERE USER_ID = @USER_ID AND CARRIER_ID = @CARRIER_ID ";
        private string SQL_DELETE_USER_CARRIER = " DELETE FROM @_@USER_CARRIER WHERE USER_ID = @USER_ID ";
        private string SQL_INSERT_USER_CARRIER = " INSERT INTO @_@USER_CARRIER ( USER_ID, CARRIER_ID, IS_DEFAULT, CREATED_BY, CREATED_DATE, UPDATED_BY,UPDATED_DATE) VALUES ( @USER_ID, @CARRIER_ID, @IS_DEFAULT, @CREATED_BY, GETDATE(), @UPDATED_BY, GETDATE())  ";
        private string SQL_SELECT_ALL_USER_CARRIER = " SELECT  ROWID, USER_ID, CARRIER_ID, IS_DEFAULT, TS, CREATED_BY, CREATED_DATE, UPDATED_BY,UPDATED_DATE  FROM  @_@USER_CARRIER ";
        private string SQL_UPDATE_USER_CARRIER = " UPDATE @_@USER_CARRIER SET IS_DEFAULT = @IS_DEFAULT, UPDATED_BY = @UPDATED_BY ,UPDATED_DATE=GETDATE()  WHERE USER_ID = @USER_ID AND CARRIER_ID = @CARRIER_ID  ";
        private string TS = "@TS";
        private string UPDATED_BY = "@UPDATED_BY";
        private string USER_ID = "@USER_ID";

        public bool CheckUserCarrierIDUnique(string userID, string CarrierID, string whLoginID)
        {
            SqlParameter[] paras = new SqlParameter[] { new SqlParameter("@USER_ID", userID), new SqlParameter("@CARRIER_ID", CarrierID) };
            return (DBHelper.ExecuteScalar(CommandType.Text, this.SQL_CHECK_USER_CARRIER_ID_UNIQUE.Replace("@_@", whLoginID), paras).ToString() == "1");
        }

        public bool CheckUserCarrierIDUnique(DataBase dataBase, DbTransaction tran, string userID, string CarrierID, string whLoginID)
        {
            SqlParameter[] paras = new SqlParameter[] { new SqlParameter("@USER_ID", userID), new SqlParameter("@CARRIER_ID", CarrierID) };
            return (dataBase.ExecuteScalar(tran, CommandType.Text, this.SQL_CHECK_USER_CARRIER_ID_UNIQUE.Replace("@_@", whLoginID), paras).ToString() == "1");
        }

        public int DeleteUserCarrier(string userID, string CarrierID, string whLoginID)
        {
            string strSql = this.SQL_DELETE_USER_CARRIER.Replace("@_@", whLoginID) + " AND CARRIER_ID = @CARRIER_ID";
            int result = 0;
            DataBase dataBase = new DataBase();
            DbConnection conn = dataBase.connection;
            conn.Open();
            DbTransaction tran = conn.BeginTransaction();
            try
            {
                SqlParameter[] paras = new SqlParameter[] { new SqlParameter("@USER_ID", userID), new SqlParameter("@CARRIER_ID", CarrierID) };
                result += dataBase.ExecuteNonQuery(tran, CommandType.Text, strSql, paras);
                tran.Commit();
            }
            catch (SqlException sqlEx)
            {
                tran.Rollback();
                CommonErrorHandler.ErrorHandler(sqlEx, LogType.Error);
            }
            finally
            {
                conn.Close();
            }
            return result;
        }

        public int DeleteUserCarrier(DataBase dataBase, DbTransaction tran, string userID, string whLoginID)
        {
            int result = 0;
            try
            {
                SqlParameter[] paras = new SqlParameter[] { new SqlParameter("@USER_ID", userID) };
                result += dataBase.ExecuteNonQuery(tran, CommandType.Text, this.SQL_DELETE_USER_CARRIER.Replace("@_@", whLoginID), paras);
            }
            catch (SqlException sqlEx)
            {
                CommonErrorHandler.ErrorHandler(sqlEx, LogType.Error);
            }
            return result;
        }

        public int DeleteUserCarrier(DataBase dataBase, DbTransaction tran, string userID, string CarrierID, string whLoginID)
        {
            string strSql = this.SQL_DELETE_USER_CARRIER.Replace("@_@", whLoginID) + " AND CARRIER_ID = @CARRIER_ID";
            int result = 0;
            try
            {
                SqlParameter[] paras = new SqlParameter[] { new SqlParameter("@USER_ID", userID), new SqlParameter("@CARRIER_ID", CarrierID) };
                result += dataBase.ExecuteNonQuery(tran, CommandType.Text, strSql, paras);
            }
            catch (SqlException sqlEx)
            {
                CommonErrorHandler.ErrorHandler(sqlEx, LogType.Error);
            }
            return result;
        }

        public DataSet GetAllUserCarrier(string whLoginID)
        {
            string sql = this.SQL_SELECT_ALL_USER_CARRIER.Replace("@_@", whLoginID);
            return DBHelper.ExecuteDataSet(CommandType.Text, sql);
        }

        public DataSet GetAllUserCarrier(DataBase dataBase, DbTransaction tran, string whLoginID)
        {
            string sql = this.SQL_SELECT_ALL_USER_CARRIER.Replace("@_@", whLoginID);
            return dataBase.ExecuteDataSet(tran, CommandType.Text, sql);
        }

        public List<UserCarrierInfo> GetAuthorizedCarrierByUserID(string userID, string whLoginID)
        {
            List<UserCarrierInfo> UserCarrierList = new List<UserCarrierInfo>();
            StringBuilder StrSql = new StringBuilder();
            StrSql.AppendFormat("SELECT  C.CARRIER_ID,C.COMPANY,UC.IS_DEFAULT FROM {1}CARRIER C  INNER JOIN  SYSADM.USER_CARRIER UC ON C.CARRIER_ID = UC.CARRIER_ID WHERE UC.USER_ID='{0}'", userID, whLoginID);
            using (IDataReader reader = DBHelper.ExecuteReader(CommandType.Text, StrSql.ToString()))
            {
                UserCarrierInfo userCarrierInfo = null;
                while (reader.Read())
                {
                    userCarrierInfo = new UserCarrierInfo(reader["CARRIER_ID"].ToString(), reader["COMPANY"].ToString(), reader["IS_DEFAULT"].ToString());
                    UserCarrierList.Add(userCarrierInfo);
                }
            }
            return UserCarrierList;
        }

        public UserCarrierInfo GetCarrierByUserID(string userID)
        {
            StringBuilder StrSql = new StringBuilder();
            StrSql.AppendFormat("SELECT CARRIER_ID,IS_DEFAULT FROM SYSADM.USER_CARRIER WHERE IS_DEFAULT='Y' AND USER_ID='{0}'", userID);
            UserCarrierInfo userCarrierInfo = null;
            using (IDataReader reader = DBHelper.ExecuteReader(CommandType.Text, StrSql.ToString()))
            {
                while (reader.Read())
                {
                    userCarrierInfo = new UserCarrierInfo(reader["CARRIER_ID"].ToString(), "", reader["IS_DEFAULT"].ToString());
                }
            }
            return userCarrierInfo;
        }

        public List<UserCarrierInfo> GetUnauthorizedCarrierByUserID(string userID, string whLoginID)
        {
            List<UserCarrierInfo> UserCarrierList = new List<UserCarrierInfo>();
            StringBuilder StrSql = new StringBuilder();
            StrSql.AppendFormat("   SELECT  C.CARRIER_ID,C.COMPANY, ''AS IS_DEFAULT  FROM {1}CARRIER C  WHERE C.CARRIER_ID NOT IN( SELECT CARRIER_ID FROM SYSADM.USER_CARRIER WHERE USER_ID='{0}')", userID, whLoginID);
            using (IDataReader reader = DBHelper.ExecuteReader(CommandType.Text, StrSql.ToString()))
            {
                UserCarrierInfo userCarrierInfo = null;
                while (reader.Read())
                {
                    userCarrierInfo = new UserCarrierInfo(reader["CARRIER_ID"].ToString(), reader["COMPANY"].ToString(), reader["IS_DEFAULT"].ToString());
                    UserCarrierList.Add(userCarrierInfo);
                }
            }
            return UserCarrierList;
        }

        public UserCarrierInfo GetUserCarrierByID(string userID, string carrierID, string whLoginID)
        {
            string sql = this.SQL_SELECT_ALL_USER_CARRIER.Replace("@_@", whLoginID) + " WHERE USER_ID = @USER_ID AND CARRIER_ID = @CARRIER_ID  ";
            SqlParameter[] paras = new SqlParameter[] { new SqlParameter("@USER_ID", userID), new SqlParameter("@CARRIER_ID", carrierID) };
            UserCarrierInfo userCarrierInfo = null;
            using (IDataReader reader = DBHelper.ExecuteReader(CommandType.Text, sql, paras))
            {
                if (reader.Read())
                {
                    userCarrierInfo = new UserCarrierInfo((reader["ROWID"].ToString() != "") ? int.Parse(reader["ROWID"].ToString()) : 0, reader["USER_ID"].ToString(), reader["CARRIER_ID"].ToString(), reader["IS_DEFAULT"].ToString(), (byte[]) reader["TS"], reader["CREATED_BY"].ToString(), (reader["CREATED_DATE"].ToString() != "") ? DateTime.Parse(reader["CREATED_DATE"].ToString()) : new DateTime(), reader["UPDATED_BY"].ToString(), (reader["UPDATED_DATE"].ToString() != "") ? DateTime.Parse(reader["UPDATED_DATE"].ToString()) : new DateTime());
                }
            }
            return userCarrierInfo;
        }

        public UserCarrierInfo GetUserCarrierByID(DataBase dataBase, DbTransaction tran, string userID, string carrierID, string whLoginID)
        {
            string sql = this.SQL_SELECT_ALL_USER_CARRIER.Replace("@_@", whLoginID) + " WHERE USER_ID = @USER_ID AND CARRIER_ID = @CARRIER_ID  ";
            SqlParameter[] paras = new SqlParameter[] { new SqlParameter("@USER_ID", userID), new SqlParameter("@CARRIER_ID", carrierID) };
            UserCarrierInfo userCarrierInfo = null;
            IDataReader reader = dataBase.ExecuteReader(tran, CommandType.Text, sql, paras);
            if (reader.Read())
            {
                userCarrierInfo = new UserCarrierInfo((reader["ROWID"].ToString() != "") ? int.Parse(reader["ROWID"].ToString()) : 0, reader["USER_ID"].ToString(), reader["CARRIER_ID"].ToString(), reader["IS_DEFAULT"].ToString(), (byte[]) reader["TS"], reader["CREATED_BY"].ToString(), (reader["CREATED_DATE"].ToString() != "") ? DateTime.Parse(reader["CREATED_DATE"].ToString()) : new DateTime(), reader["UPDATED_BY"].ToString(), (reader["UPDATED_DATE"].ToString() != "") ? DateTime.Parse(reader["UPDATED_DATE"].ToString()) : new DateTime());
            }
            if (!reader.IsClosed)
            {
                reader.Close();
            }
            return userCarrierInfo;
        }

        public DataSet GetUserCarrierByQueryList(List<string> sqlWhere, UserCarrierQueryEntity uservendorQuery, string whLoginID)
        {
            string temp = this.SQL_SELECT_ALL_USER_CARRIER.Replace("@_@", whLoginID);
            for (int i = 0; i < sqlWhere.Count; i++)
            {
                if (i == 0)
                {
                    temp = temp + " WHERE " + sqlWhere[i].ToString();
                }
                else
                {
                    temp = temp + " AND " + sqlWhere[i].ToString();
                }
            }
            if (!uservendorQuery.IsGetAll)
            {
                temp = PagingHelper.GetPagingSQL(temp, uservendorQuery.CurrentPage, uservendorQuery.PageSize, uservendorQuery.SortField, uservendorQuery.SortDirection);
            }
            return DBHelper.ExecuteDataSet(CommandType.Text, temp);
        }

        public DataSet GetUserCarrierByQueryList(DataBase dataBase, DbTransaction tran, List<string> sqlWhere, UserCarrierQueryEntity uservendorQuery, string whLoginID)
        {
            string temp = this.SQL_SELECT_ALL_USER_CARRIER.Replace("@_@", whLoginID);
            for (int i = 0; i < sqlWhere.Count; i++)
            {
                if (i == 0)
                {
                    temp = temp + " WHERE " + sqlWhere[i].ToString();
                }
                else
                {
                    temp = temp + " AND " + sqlWhere[i].ToString();
                }
            }
            temp = PagingHelper.GetPagingSQL(temp, uservendorQuery.CurrentPage, uservendorQuery.PageSize, uservendorQuery.SortField, uservendorQuery.SortDirection);
            return dataBase.ExecuteDataSet(tran, CommandType.Text, temp);
        }

        public int InsertUserCarrier(UserCarrierInfo userCarrierInfo, string whLoginID)
        {
            int result = 0;
            DataBase db = new DataBase();
            DbConnection conn = db.connection;
            conn.Open();
            DbTransaction tran = conn.BeginTransaction();
            try
            {
                SqlParameter[] paras = this.Set_UserCarrier_Parameters(userCarrierInfo);
                if (paras != null)
                {
                    result += db.ExecuteNonQuery(tran, CommandType.Text, this.SQL_INSERT_USER_CARRIER.Replace("@_@", whLoginID), paras);
                }
                tran.Commit();
            }
            catch (SqlException sqlEx)
            {
                tran.Rollback();
                CommonErrorHandler.ErrorHandler(sqlEx, LogType.Error);
            }
            finally
            {
                conn.Close();
            }
            return result;
        }

        public int InsertUserCarrier(DataBase dataBase, DbTransaction tran, UserCarrierInfo userCarrierInfo, string whLoginID)
        {
            int result = 0;
            try
            {
                SqlParameter[] paras = this.Set_UserCarrier_Parameters(userCarrierInfo);
                if (paras != null)
                {
                    result += dataBase.ExecuteNonQuery(tran, CommandType.Text, this.SQL_INSERT_USER_CARRIER.Replace("@_@", whLoginID), paras);
                }
            }
            catch (SqlException sqlEx)
            {
                CommonErrorHandler.ErrorHandler(sqlEx, LogType.Error);
            }
            return result;
        }

        private SqlParameter[] Set_UserCarrier_Parameters(UserCarrierInfo userCarrierInfo)
        {
            SqlParameter[] paramArray = new SqlParameter[] { new SqlParameter(this.USER_ID, SqlDbType.VarChar, 20), new SqlParameter(this.CARRIER_ID, SqlDbType.VarChar, 20), new SqlParameter(this.IS_DEFAULT, SqlDbType.VarChar, 1), new SqlParameter(this.CREATED_BY, SqlDbType.VarChar, 20), new SqlParameter(this.UPDATED_BY, SqlDbType.VarChar, 20) };
            paramArray[0].Value = userCarrierInfo.UserID;
            paramArray[1].Value = userCarrierInfo.CarrierID;
            if (!string.IsNullOrEmpty(userCarrierInfo.IsDefault))
            {
                paramArray[2].Value = userCarrierInfo.IsDefault;
            }
            else
            {
                paramArray[2].Value = DBNull.Value;
            }
            paramArray[3].Value = userCarrierInfo.CreatedBy;
            paramArray[4].Value = userCarrierInfo.UpdatedBy;
            return paramArray;
        }

        public int UpdateUserCarrier(UserCarrierInfo userCarrierInfo, string whLoginID)
        {
            int result = 0;
            DataBase db = new DataBase();
            DbConnection conn = db.connection;
            conn.Open();
            DbTransaction tran = conn.BeginTransaction();
            try
            {
                SqlParameter[] paras = this.Set_UserCarrier_Parameters(userCarrierInfo);
                if (paras != null)
                {
                    result += db.ExecuteNonQuery(tran, CommandType.Text, this.SQL_UPDATE_USER_CARRIER.Replace("@_@", whLoginID), paras);
                }
                tran.Commit();
            }
            catch (SqlException sqlEx)
            {
                tran.Rollback();
                CommonErrorHandler.ErrorHandler(sqlEx, LogType.Error);
            }
            finally
            {
                conn.Close();
            }
            return result;
        }

        public int UpdateUserCarrier(DataBase dataBase, DbTransaction tran, UserCarrierInfo userCarrierInfo, string whLoginID)
        {
            int result = 0;
            try
            {
                SqlParameter[] paras = this.Set_UserCarrier_Parameters(userCarrierInfo);
                if (paras != null)
                {
                    result += dataBase.ExecuteNonQuery(tran, CommandType.Text, this.SQL_UPDATE_USER_CARRIER.Replace("@_@", whLoginID), paras);
                }
            }
            catch (SqlException sqlEx)
            {
                CommonErrorHandler.ErrorHandler(sqlEx, LogType.Error);
            }
            return result;
        }
    }
}

